package com.jinzhi.jzweb.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.jinzhi.api.exception.IFastApiException;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.common.controller.ApittController;
import com.jinzhi.jzapi.common.pojo.CerUtilsVo;
import com.jinzhi.jzapi.utils.ITextPdfUtil;
import com.jinzhi.jzweb.domain.CoursesDO;
import com.jinzhi.jzweb.domain.TrainingCertificatesDO;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.pojo.TrainingCerVo;
import com.jinzhi.jzweb.service.CertificateProfileService;
import com.jinzhi.jzweb.service.CoursesService;
import com.jinzhi.jzweb.service.TrainingCertificatesService;
import com.jinzhi.jzweb.utils.FileUtil;
import com.jinzhi.jzweb.utils.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.*;

/**
 * <pre>
 * 培训证书
 * </pre>
 * <small> 2020-06-02 09:10:46 | lance</small>
 */
@Slf4j
@Controller
@RequestMapping("/jzweb/trainingCertificates")
public class TrainingCertificatesController extends BaseController {
    @Autowired
    private TrainingCertificatesService trainingCertificatesService;
    @Autowired
    private UserService userService;
    @Autowired
    private CoursesService coursesService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private DictService dictService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private ApittController apittController;
    private String RecoveryId="1375327865662226434";//产后恢复证书ID

    @GetMapping()
    @RequiresPermissions("jzweb:trainingCertificates:trainingCertificates")
    String TrainingCertificates(Model model) {
        model.addAttribute("cprofileIds", certificateProfileService.selByAll());
        model.addAttribute("regionAll", certificateProfileService.selregionAll());
        return "jzweb/trainingCertificates/trainingCertificates";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:trainingCertificates:trainingCertificates")
    public Result<Page<TrainingCertificatesDO>> list(HttpServletRequest req, TrainingCertificatesDO trainingCertificatesDTO) {
        Wrapper<TrainingCertificatesDO> wrapper = new EntityWrapper<TrainingCertificatesDO>().orderBy("id", false);
        if (trainingCertificatesDTO.getState() != null) {
            wrapper.eq("state", trainingCertificatesDTO.getState());
        }
        if (trainingCertificatesDTO.getNumbers() != null) {
            wrapper.like("numbers", trainingCertificatesDTO.getNumbers());
        }
        if (StringUtils.isNotBlank(trainingCertificatesDTO.getUserName())) {
            Wrapper<UserDO> uWrapper = new EntityWrapper<UserDO>().like("name", trainingCertificatesDTO.getUserName());
            List<UserDO> userDOS = userService.selectList(uWrapper);
            String str = "";
            for (UserDO userDO : userDOS) {
                str = str + userDO.getId() + ",";

            }
            wrapper.and();
            if (StringUtils.isNotBlank(str)) {
                wrapper.in("user_id", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("user_id", null);
            }
        }
        String strr = roleCourse(req, trainingCertificatesDTO.getCoursesName());
        if (org.apache.commons.lang.StringUtils.isBlank(strr)) {
            wrapper.and();
            wrapper.eq("courses_id", null);
        } else if (!strr.equals("@#$%^&*!~")) {
            wrapper.and();
            wrapper.in("courses_id", strr.substring(0, strr.length() - 1));
        }

        Page<TrainingCertificatesDO> page = trainingCertificatesService.selectPage(getPage(TrainingCertificatesDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            TrainingCertificatesDO obj = (TrainingCertificatesDO) page.getRecords().get(i);
            if (obj.getUserId() != null) {
                UserDO userDO = userService.selectById(obj.getUserId());
                if (userDO != null) {
                    obj.setUserName(userDO.getName());
                }
            }
            if (obj.getCoursesId() != null) {
                CoursesDO coursesDO = coursesService.selectById(obj.getCoursesId());
                if (coursesDO != null) {
                    obj.setCoursesName(coursesDO.getName());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:trainingCertificates:add")
    String add() {
        return "jzweb/trainingCertificates/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:trainingCertificates:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        TrainingCertificatesDO trainingCertificates = trainingCertificatesService.selectById(id);
        model.addAttribute("trainingCertificates", trainingCertificates);
        return "jzweb/trainingCertificates/edit";
    }

    @Log("添加培训证书")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:trainingCertificates:add")
    public Result<String> save(TrainingCertificatesDO trainingCertificates) {
        trainingCertificatesService.insert(trainingCertificates);
        return Result.ok();
    }

    @Log("修改培训证书")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:trainingCertificates:edit")
    public Result<String> update(TrainingCertificatesDO trainingCertificates) {
        boolean update = trainingCertificatesService.updateById(trainingCertificates);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除培训证书")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:trainingCertificates:remove")
    public Result<String> remove(Long id) {
        trainingCertificatesService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除培训证书")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:trainingCertificates:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        trainingCertificatesService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

    /**
     * 下载导入模板
     *
     * @param response
     */
    @RequestMapping("/downloadImportTemplate")
    @RequiresPermissions("jzweb:trainingCertificates:import")
    @ResponseBody
    public void downloadImportTemplate(HttpServletResponse response) {
        List<TrainingCerVo> list = new LinkedList<>();
        //导出操作
        EasyPoiUtil.exportExcel(list, "培训证书信息导入模板", "培训证书信息导入模板", TrainingCerVo.class, "培训证书信息导入模板", response);
    }

    /**
     * 培训证书信息导入
     *
     * @param file excel文件,cType:专家类型（0师资，1考评员）
     */
    @Log("培训证书信息导入")
    @PostMapping("/import")
    @ResponseBody
    @Transactional
    @RequiresPermissions("jzweb:trainingCertificates:import")
    public Result<?> importExcel(@RequestParam("file") MultipartFile file, String cprofileId, String cType,String dateAdd) {
        //---------------------------------检测导入信息及条件-----------------------------------------
        //第一步--判断文件格式
        if (!"application/vnd.ms-excel".equals(file.getContentType())) {
            return Result.fail("文件格式错误，请选择.xls文件");
        }

        //第二步--解析文件获得数据
        List<TrainingCerVo> list = EasyPoiUtil.importExcel(file, 1, 1, TrainingCerVo.class);
        if (list.size() == 0) {
            return Result.fail("Excel数据为空，请完善");
        }

        if (StringUtils.isBlank(cprofileId)) {
            return Result.fail("培训证书信息未选择，请选择后导入！");
        }
        if (StringUtils.isBlank(cType)) {
            return Result.fail("专家类型未选择，请选择后导入！");
        }

        Map map = new HashMap();
        if(cType.equals("2")){
            map.put("name", "考务技术员证");
            map.put("type", "tra_axa_synthesis");
        }else if(cType.equals("4")){
            map.put("name", "督导员证");
            map.put("type", "tra_supervisor_synthesis");
        }else if(cType.equals("3")){
            map.put("name", "考务技术员结业证");
            map.put("type", "tra_axa_grad");
        }else if(cType.equals("5")){
            map.put("name", "督导员结业证");
            map.put("type", "tra_supervisor_grad");
        }
        //获取背景图片
        else if(cprofileId.equals(RecoveryId)){
            if (cType.equals("0")) {
                map.put("name", "师资证-产后恢复");
                map.put("type", "tra_tea_synthesis_recovery");
            } else if(cType.equals("1")) {
                map.put("name", "考评员证-产后恢复");
                map.put("type", "tra_exa_synthesis_recovery");
            }
        }else{
            if (cType.equals("0")) {
                map.put("name", "师资证-幼儿照护");
                map.put("type", "tra_tea_synthesis");
            } else if(cType.equals("1")) {
                map.put("name", "考评员证-幼儿照护");
                map.put("type", "tra_exa_synthesis");
            }
        }

        String traSynthesis = dictService.selDicBy(map);
        if (StringUtils.isNotBlank(traSynthesis)) {
            traSynthesis = ValuesUtil.localUrl + traSynthesis;
        }

        String electronicSeal = null;
        String effectiveDate = null;
        if (cType.equals("0")||cType.equals("3")||cType.equals("5")) {
            //获取电子公章
            map.clear();
            map.put("name", "金职电子公章");
            map.put("type", "electronic_seal");
            electronicSeal = dictService.selDicBy(map);
            if (StringUtils.isNotBlank(electronicSeal)) {
                electronicSeal = ValuesUtil.localUrl + electronicSeal;
            }
        } else {
            //获取证书有效时长
            map.clear();
            map.put("name", "培训证书有效时长");
            map.put("type", "tra_cer_time");
            String traCerTime = dictService.selDicBy(map);
            if (StringUtils.isNotBlank(traCerTime)) {
                //判断是否为数字
                if (!IdCardUtil.isNumeric(traCerTime)) {
                    return Result.fail("数据字典配置错误，培训证书有效时长请填写阿拉伯数字，例如：1、2、3;");
                }
            } else {
                traCerTime = "3";
            }
            String string = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            LocalDate today = LocalDate.now();
            LocalDate timeDay = today.plus(Integer.parseInt(traCerTime), ChronoUnit.YEARS);
            effectiveDate = string + "至" + timeDay;
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNow =dateAdd;
        //具体的年、月、日可利用substring截取
        //dateNow.substring(开始下标，结束下标),下标原则：从0开始，包前不包后
        String cerYear = dateNow.substring(0, 4);
        String cerMath = dateNow.substring(5, 7);
        String cerDay = dateNow.substring(8, 10);

        //证书编号
        String cerNumEnd = "JZ";

//        //证书名称
//        String cerName = "幼儿照护";
//        CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(Long.parseLong(cprofileId));
//        if (certificateProfileDO != null) {
//            if (certificateProfileDO.getName().length() > 4) {
//                cerName = certificateProfileDO.getName().substring(0, 4);
//            } else {
//                cerName = certificateProfileDO.getName();
//            }
//        }

        FileUtil fileUtil = new FileUtil();

        //---------------------------------验证数据并导入-----------------------------------------
        //数据该表第三行，第一行标题，第二行表头
        int startRow = 3;
        int cout = 1;//错误信息计数
        List<TrainingCertificatesDO> traCerDOList = new ArrayList<>();
        List<ErrorCodeVo> list1 = new ArrayList<>();
        List<CerUtilsVo> cerUtilsVos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            UserDO rrUserDo = null;
            UserDO rsUserDo = null;
            //证书编号
            
            String cerNumbers = null;
            //证书图片
            String cerImgUrl = null;
            String cerImgUrlNoSale = null;
            CerUtilsVo cerUtilsVo = new CerUtilsVo();
            StringBuilder sb = new StringBuilder();
            //第一步验证是否存在空值
            if (StringUtils.isBlank(list.get(i).getNumPeriods())) {
                sb.append("第" + (i + startRow) + "行考核期数未填写，请完善！" + ";");
            } else {
                if (list.get(i).getTraPeriod() == null) {
                    sb.append("第" + (i + startRow) + "行培训时间未填写，请完善！" + ";");
                } else {
                    if (StringUtils.isBlank(list.get(i).getGrade())) {
                        sb.append("第" + (i + startRow) + "行证书等级未填写，请完善！" + ";");
                    } else {
                        if (StringUtils.isBlank(list.get(i).getProvince())) {
                            sb.append("第" + (i + startRow) + "行开班区域 （省份）未填写，请完善！" + ";");
                        } else {
                            if (StringUtils.isBlank(list.get(i).getStuName())) {
                                sb.append("第" + (i + startRow) + "行学生姓名未填写，请完善！" + ";");
                            } else {
                                if (StringUtils.isBlank(list.get(i).getStuMobile())) {
                                    sb.append("第" + (i + startRow) + "行学生手机号码未填写，请完善！" + ";");
                                } else {
                                    if (StringUtils.isBlank(list.get(i).getIdCard())) {
                                        sb.append("第" + (i + startRow) + "行学生身份证号码未填写，请完善！" + ";");
                                    } else {
                                        if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getImageUrl())) {
                                            sb.append("第" + (i + startRow) + "行学生寸照未填入或不在单元格内，请完善！" + ";");
                                        } else {
//                                            if (!FilesSizeUtil.imgJudge(list.get(i).getImageUrl())) {
//                                                sb.append("第" + (i + startRow) + "行学生寸照格式错误，请插入像素为295*413且大小不超过1M（一兆）的一寸照！" + ";");
//                                            } else {
                                                if (!IdCardUtil.isNumeric(list.get(i).getNumPeriods())) {
                                                    sb.append("第" + (i + startRow) + "行考核期数格式错误，只能填数字！" + ";");
                                                } else {
                                                        //第二步验证电话号码
                                                        if (!ValidUtils.isMobile(list.get(i).getStuMobile())) {
                                                            sb.append("第" + (i + startRow) + "行手机号码格式错误，请修改！" + ";");
                                                        } else {
                                                            //第三步验证身份证号码
                                                            if (!ValidUtils.isIDCard(list.get(i).getIdCard())) {
                                                                sb.append("第" + (i + startRow) + "行身份证号码格式错误，请修改！" + ";");
                                                            } else {
                                                                //第四步排重验证（自身比较）
                                                                for (int j = 0; j < list.size(); j++) {
                                                                    if (i != j) {
                                                                            if (list.get(i).getStuMobile().trim().equals(list.get(j).getStuMobile().trim())) {
                                                                                sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行手机号重复，重复值：" + list.get(i).getStuMobile() + ";");
                                                                            }
                                                                            if (list.get(i).getIdCard().trim().equals(list.get(j).getIdCard().trim())) {
                                                                                sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行身份证号码重复，重复值：" + list.get(i).getIdCard() + ";");
                                                                            }
                                                                    }
                                                                }
                                                                String dateNow1 = sdf.format(list.get(i).getTraPeriod());
                                                                String traYear = dateNow1.substring(0, 4);
                                                                String traMath = dateNow1.substring(5, 7);
                                                                String traDay = dateNow1.substring(8, 10);
                                                                //获取当前年份后两位
                                                                String yearRe = traYear.substring(2,4);

                                                                //证书编号
                                                                if(list.get(i).getNumbers()==null) {
                                                                	cerNumbers = comNumber1(cerNumEnd, list.get(i).getGrade().trim(), list.get(i).getProvince().trim(), Integer.parseInt(list.get(i).getNumPeriods().trim()), yearRe, traMath,cprofileId);
                                                                	if (cerNumbers.contains("填写错误")) {
                                                                    	sb.append("第" + (i + startRow) + "行" + cerNumbers + ";");
                                                                	}
                                                                	int cerEnd = 0;
                                                                	Object cerNumberss;
                                                                	if (cType.equals("0")) {
                                                                    	cerNumberss = EhCacheUtil.get("cerNumberTra" + list.get(i).getProvince());
                                                                	} else {
                                                                    	cerNumberss = EhCacheUtil.get("cerNumberExa" + list.get(i).getProvince());
                                                                	}

                                                                	if (cerNumberss == null) {
                                                                    	//查询出该证书编号最大值
                                                                    	String cerNumber = trainingCertificatesService.selCerNumber(cerNumbers);
                                                                    	if (StringUtils.isNotBlank(cerNumber)) {
                                                                        	cerEnd = Integer.parseInt(cerNumber.substring(cerNumber.length() - 4));
                                                                    	}
                                                                	} else {
                                                                    	cerEnd = (Integer) cerNumberss;
                                                                	}
                                                                	if (cType.equals("0")) {
                                                                    	EhCacheUtil.put("cerNumberTra" + list.get(i).getProvince(), cerEnd + 1);
                                                                	} else {
                                                                    	EhCacheUtil.put("cerNumberExa" + list.get(i).getProvince(), cerEnd + 1);
                                                                	}
                                                                	cerNumbers = cerNumbers + WithZoreUtil.frontCompWithZore(cerEnd + 1, 4);
                                                                }else {
                                                                	cerNumbers=list.get(i).getNumbers();
                                                                	if(StringUtils.isNotBlank(trainingCertificatesService.selByCerNumber(cerNumbers))) {
                                                                		sb.append("第" + (i + startRow) + "行,证件编号已存在;");
                                                                	}
                                                                	
                                                                }
                                                                if (cType.equals("0")) {
                                                                    //师资证书
                                                                    if (StringUtils.isBlank(list.get(i).getCourseHours())) {
                                                                        sb.append("第" + (i + startRow) + "行课程学时未填写，请完善！" + ";");
                                                                    } else {
                                                                        //判断是否为数字
                                                                        if (!IdCardUtil.isNumeric(list.get(i).getCourseHours())) {
                                                                            sb.append("第" + (i + startRow) + "行课程学时(" + list.get(i).getCourseHours() + ")填写错误，请填写阿拉伯数字，例如：01或11！" + ";");
                                                                        } else {
                                                                            cerUtilsVo.setType(0);
                                                                            cerUtilsVo.setBackgroundPath(traSynthesis);
                                                                            cerUtilsVo.setStuName(list.get(i).getStuName());
                                                                            cerUtilsVo.setStuImg(list.get(i).getImageUrl());
                                                                            cerUtilsVo.setIdCard(list.get(i).getIdCard());
                                                                            cerUtilsVo.setCerNumber(cerNumbers);
                                                                            cerUtilsVo.setNumPeriods(WithZoreUtil.frontCompWithZore(Integer.parseInt(list.get(i).getNumPeriods()), 2));
                                                                            cerUtilsVo.setTrainingNumber(list.get(i).getCourseHours());
                                                                            cerUtilsVo.setTraYear(traYear);
                                                                            cerUtilsVo.setTraMath(traMath);
                                                                            cerUtilsVo.setTraDay(traDay);
                                                                            cerUtilsVo.setCerYear(cerYear);
                                                                            cerUtilsVo.setCerMath(cerMath);
                                                                            cerUtilsVo.setCerDay(cerDay);
                                                                            cerUtilsVo.setElectronicSeal(electronicSeal);
                                                                            cerUtilsVo.setWorkUnit(list.get(i).getWorkUnit());
                                                                            cerUtilsVo.setGrade(0);
                                                                            if(list.get(i).getGrade().contains("高级")) {
                                                                                if(cprofileId.equals(RecoveryId)){
                                                                                    map.put("name", "高级师资证-产后恢复");
                                                                                    map.put("type", "tra_tea_synthesis_high_recovery");
                                                                                }else{
                                                                                    map.put("name", "高级师资证-幼儿照护");
                                                                                    map.put("type", "tra_tea_synthesis_high");
                                                                                }
                                                                                cerUtilsVo.setGrade(1);
                                                                                String t = dictService.selDicBy(map);
                                                                                if (StringUtils.isNotBlank(t)) {
                                                                                    t = ValuesUtil.localUrl + t;
                                                                                }
                                                                                cerUtilsVo.setBackgroundPath(t);
                                                                                cerUtilsVo.setGrade(1);
                                                                            }

//                                                                            try {
//                                                                                //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
//                                                                                if(list.get(i).getGrade().equals("高级师资")) {
//                                                                                    map.put("name", "高级师资背景图");
//                                                                                    map.put("type", "tra_tea_synthesis_high");
//                                                                                    traSynthesis = dictService.selDicBy(map);
//                                                                                    if (StringUtils.isNotBlank(traSynthesis)) {
//                                                                                        traSynthesis = ValuesUtil.localUrl + traSynthesis;
//                                                                                      }
//                                                                                    cerImgUrl = CerSynthesisUtil.overTrainingHighImage(0, traSynthesis, list.get(i).getStuName(), list.get(i).getImageUrl(), list.get(i).getIdCard(), cerNumbers,
//                                                                                            WithZoreUtil.frontCompWithZore(Integer.parseInt(list.get(i).getNumPeriods()), 2), list.get(i).getCourseHours(), traYear, traMath, traDay,
//                                                                                            cerYear, cerMath, cerDay, electronicSeal);
//                                                                                    cerImgUrlNoSale = CerSynthesisUtil.overTrainingHighImage(1, traSynthesis, list.get(i).getStuName(), list.get(i).getImageUrl(), list.get(i).getIdCard(), cerNumbers,
//                                                                                            WithZoreUtil.frontCompWithZore(Integer.parseInt(list.get(i).getNumPeriods()), 2), list.get(i).getCourseHours(), traYear, traMath, traDay,
//                                                                                            cerYear, cerMath, cerDay, electronicSeal);
//                                                                                }
//                                                                               else {
//                                                                                    cerImgUrl = CerSynthesisUtil.overTrainingImage(0, traSynthesis, list.get(i).getStuName(), list.get(i).getImageUrl(), list.get(i).getIdCard(), cerNumbers,
//                                                                                            WithZoreUtil.frontCompWithZore(Integer.parseInt(list.get(i).getNumPeriods()), 2), list.get(i).getCourseHours(), traYear, traMath, traDay,
//                                                                                            cerYear, cerMath, cerDay, electronicSeal);
//                                                                                    cerImgUrlNoSale = CerSynthesisUtil.overTrainingImage(1, traSynthesis, list.get(i).getStuName(), list.get(i).getImageUrl(), list.get(i).getIdCard(), cerNumbers,
//                                                                                            WithZoreUtil.frontCompWithZore(Integer.parseInt(list.get(i).getNumPeriods()), 2), list.get(i).getCourseHours(), traYear, traMath, traDay,
//                                                                                            cerYear, cerMath, cerDay, electronicSeal);
//                                                                                }
//                                                                            } catch (IOException e) {
//                                                                                e.printStackTrace();
//                                                                            }
                                                                        }
                                                                    }
                                                                } 
                                                                else if(cType.equals("1")){

                                                                    cerUtilsVo.setType(1);
                                                                    cerUtilsVo.setBackgroundPath(traSynthesis);
                                                                    cerUtilsVo.setStuName(list.get(i).getStuName());
                                                                    cerUtilsVo.setStuImg(list.get(i).getImageUrl());
                                                                    cerUtilsVo.setIdCard(list.get(i).getIdCard());
                                                                    cerUtilsVo.setCerNumber(cerNumbers);
                                                                    cerUtilsVo.setEffectiveDate(effectiveDate);
                                                                    cerUtilsVo.setWorkUnit(list.get(i).getWorkUnit());
                                                                    cerUtilsVo.setGrade(0);
                                                                    if(list.get(i).getGrade().contains("高级")) {
                                                                        if(cprofileId.equals(RecoveryId)){
                                                                            map.put("name", "高级考评员证-产后恢复");
                                                                            map.put("type", "tra_exa_synthesis_high_recovery");
                                                                        }else{
                                                                            map.put("name", "高级考评员证-幼儿照护");
                                                                            map.put("type", "tra_exa_synthesis_high");
                                                                        }
                                                                        String t = dictService.selDicBy(map);
                                                                        if (StringUtils.isNotBlank(t)) {
                                                                            t = ValuesUtil.localUrl + t;
                                                                        }
                                                                        cerUtilsVo.setBackgroundPath(t);
                                                                        cerUtilsVo.setGrade(1);
                                                                    }

                                                                }else if(cType.equals("2")){
                                                                    cerUtilsVo.setType(2);
                                                                    cerUtilsVo.setBackgroundPath(traSynthesis);
                                                                    cerUtilsVo.setStuName(list.get(i).getStuName());
                                                                    cerUtilsVo.setStuImg(list.get(i).getImageUrl());
                                                                    cerUtilsVo.setIdCard(list.get(i).getIdCard());
                                                                    cerUtilsVo.setCerNumber(cerNumbers);
                                                                    cerUtilsVo.setEffectiveDate(effectiveDate);
                                                                    cerUtilsVo.setWorkUnit(list.get(i).getWorkUnit());

                                                                }else if(cType.equals("3")){
                                                                	//考务技术员-结业证书
                                                                	 if (StringUtils.isBlank(list.get(i).getCourseHours())) {
                                                                         sb.append("第" + (i + startRow) + "行课程学时未填写，请完善！" + ";");
                                                                     } else {
                                                                         //判断是否为数字
                                                                         if (!IdCardUtil.isNumeric(list.get(i).getCourseHours())) {
                                                                             sb.append("第" + (i + startRow) + "行课程学时(" + list.get(i).getCourseHours() + ")填写错误，请填写阿拉伯数字，例如：01或11！" + ";");
                                                                         } else {
                                                                             cerUtilsVo.setType(3);
                                                                             cerUtilsVo.setBackgroundPath(traSynthesis);
                                                                             cerUtilsVo.setStuName(list.get(i).getStuName());
                                                                             cerUtilsVo.setStuImg(list.get(i).getImageUrl());
                                                                             cerUtilsVo.setIdCard(list.get(i).getIdCard());
                                                                             cerUtilsVo.setCerNumber(cerNumbers);
                                                                             cerUtilsVo.setNumPeriods(WithZoreUtil.frontCompWithZore(Integer.parseInt(list.get(i).getNumPeriods()), 2));
                                                                             cerUtilsVo.setTrainingNumber(list.get(i).getCourseHours());
                                                                             cerUtilsVo.setTraYear(traYear);
                                                                             cerUtilsVo.setTraMath(traMath);
                                                                             cerUtilsVo.setTraDay(traDay);
                                                                             cerUtilsVo.setCerYear(cerYear);
                                                                             cerUtilsVo.setCerMath(cerMath);
                                                                             cerUtilsVo.setCerDay(cerDay);
                                                                             cerUtilsVo.setWorkUnit(list.get(i).getWorkUnit());
                                                                             cerUtilsVo.setElectronicSeal(electronicSeal);

                                                                         }
                                                                     }
                                                                }else if(cType.equals("4")){
                                                                	 //督导员证
                                                                    cerUtilsVo.setType(4);
                                                                    cerUtilsVo.setBackgroundPath(traSynthesis);
                                                                    cerUtilsVo.setStuName(list.get(i).getStuName());
                                                                    cerUtilsVo.setStuImg(list.get(i).getImageUrl());
                                                                    cerUtilsVo.setIdCard(list.get(i).getIdCard());
                                                                    cerUtilsVo.setWorkUnit(list.get(i).getWorkUnit());
                                                                    cerUtilsVo.setCerNumber(cerNumbers);
                                                                    cerUtilsVo.setEffectiveDate(effectiveDate);

                                                                }else{
                                                                	//督导员-结业证书
                                                                	 if (StringUtils.isBlank(list.get(i).getCourseHours())) {
                                                                         sb.append("第" + (i + startRow) + "行课程学时未填写，请完善！" + ";");
                                                                     } else {
                                                                         //判断是否为数字
                                                                         if (!IdCardUtil.isNumeric(list.get(i).getCourseHours())) {
                                                                             sb.append("第" + (i + startRow) + "行课程学时(" + list.get(i).getCourseHours() + ")填写错误，请填写阿拉伯数字，例如：01或11！" + ";");
                                                                         } else {
                                                                             cerUtilsVo.setType(5);
                                                                             cerUtilsVo.setBackgroundPath(traSynthesis);
                                                                             cerUtilsVo.setStuName(list.get(i).getStuName());
                                                                             cerUtilsVo.setStuImg(list.get(i).getImageUrl());
                                                                             cerUtilsVo.setIdCard(list.get(i).getIdCard());
                                                                             cerUtilsVo.setCerNumber(cerNumbers);
                                                                             cerUtilsVo.setNumPeriods(WithZoreUtil.frontCompWithZore(Integer.parseInt(list.get(i).getNumPeriods()), 2));
                                                                             cerUtilsVo.setTrainingNumber(list.get(i).getCourseHours());
                                                                             cerUtilsVo.setTraYear(traYear);
                                                                             cerUtilsVo.setTraMath(traMath);
                                                                             cerUtilsVo.setTraDay(traDay);
                                                                             cerUtilsVo.setCerYear(cerYear);
                                                                             cerUtilsVo.setCerMath(cerMath);
                                                                             cerUtilsVo.setCerDay(cerDay);
                                                                             cerUtilsVo.setWorkUnit(list.get(i).getWorkUnit());
                                                                             cerUtilsVo.setElectronicSeal(electronicSeal);
                                                                         }
                                                                     }
                                                                }

                                                                //转换一下图片路径，将反斜杠替换掉
                                                                String url = list.get(i).getImageUrl().replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                                                                String imgUrl = url.replace("\\", "/");//学生寸照

                                                                //第五步根据手机号码获取用户信息并判断，如没有则新建，如果则返回信息
                                                                UserDO userDO = userService.findOneByKv("mobile", list.get(i).getStuMobile().trim());
                                                                if (userDO != null) {
                                                                    userDO.setHeadPortrait(imgUrl);
                                                                    if (userDO.getName() != null) {
                                                                        if (!userDO.getName().equals(list.get(i).getStuName().trim())) {
                                                                            sb.append("第" + (i + startRow) + "行考生已注册，但姓名不一致，请修改后重试！" + ";");
                                                                        }
                                                                    } else {
                                                                        userDO.setName(list.get(i).getStuName());
                                                                    }
                                                                    if (userDO.getIdNumber() != null) {
                                                                        if (!userDO.getIdNumber().equals(list.get(i).getIdCard().trim())) {
                                                                            sb.append("第" + (i + startRow) + "行考生已注册，但身份证号码不一致，请修改后重试！" + ";");
                                                                        }
                                                                    } else {
                                                                        userDO.setIdNumber(list.get(i).getIdCard());
                                                                    }

//                                                                    userDO.setOrgId(this.getUser().getOrgId());
//                                                                    userDO.setOrgName(this.getUser().getOrgName());
                                                                    List<Long> roleIds = userRoleService.listRoleId(userDO.getId());
                                                                    
                                                                    if (roleIds != null && roleIds.size() > 0) {
                                                                        userDO.setroleIds(roleIds);
                                                                    } else {
                                                                        List<Long> list11 = new ArrayList<>();
                                                                        list11.add(56L);
                                                                        userDO.setroleIds(list11);
                                                                    }

                                                                    userService.updateById(userDO);
                                                                    rsUserDo = userDO;
                                                                } else {
                                                                    UserDO userDO1 = new UserDO();
                                                                    userDO1.setUsername(list.get(i).getStuMobile().trim());
                                                                    userDO1.setName(list.get(i).getStuName().trim());
                                                                    userDO1.setIdNumber(list.get(i).getIdCard().trim());
                                                                    userDO1.setMobile(list.get(i).getStuMobile().trim());
                                                                    userDO1.setHeadPortrait(imgUrl);

                                                                    //初始密码设为身份证号后六位
                                                                    String password = list.get(i).getIdCard().trim().substring(list.get(i).getIdCard().trim().length() - 6);
                                                                    String salt = UUIDUtils.get();
                                                                    String encodePasswd = PasswdUtils.get(password, salt);
                                                                    userDO1.setSalt(salt);
                                                                    userDO1.setPassword(encodePasswd);
                                                                    userDO1.setType(0);//默认个人会员
                                                                    userDO1.setMoney(BigDecimal.valueOf(0.0));//默认0元
                                                                    userDO1.setGmtCreate(new Date());
                                                                    userDO1.setGmtModified(userDO1.getGmtCreate());
                                                                    userDO1.setStatus(1);//默认正常
                                                                    userDO1.setSex(0L);//性别，默认未知

//                                                                    userDO1.setOrgId(this.getUser().getOrgId());
//                                                                    userDO1.setOrgName(this.getUser().getOrgName());

                                                                    List<Long> roleIds = userRoleService.listRoleId(userDO1.getId());
                                                                    if (roleIds != null && roleIds.size() > 0) {
                                                                        userDO1.setroleIds(roleIds);
                                                                    } else {
                                                                        List<Long> list11 = new ArrayList<>();
                                                                        list11.add(56L);
                                                                        userDO1.setroleIds(list11);
                                                                    }
                                                                    rrUserDo = userDO1;
                                                                }


                                                            }
                                                        }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
//                    }
                }
            }


            if (sb.length() > 0) {
                if (cType.equals("0")) {
                    if (i > 1) {
                        EhCacheUtil.put("cerNumberTra" + list.get(i - 1).getProvince().trim(), null);
                    }
                } else {
                    if (i > 1) {
                        EhCacheUtil.put("cerNumberExa" + list.get(i - 1).getProvince().trim(), null);
                    }
                }
                ErrorCodeVo errorCodeVo = new ErrorCodeVo();
                errorCodeVo.setSeq(cout);
                cout += 1;
                errorCodeVo.setErrorCode(sb.toString());
                list1.add(errorCodeVo);
            } else {
                if (rrUserDo != null) {
                    boolean cc = userService.insertNoPW(rrUserDo);
                    if (!cc) {
                        log.info("第" + (i + startRow) + "行考生用户信息导入失败，建议删除重新导入！" + ";");
                    }
                } else {
                    boolean cc = userService.updateById(rsUserDo);
                    if (!cc) {
                        log.info("第" + (i + startRow) + "行考生用户信息修改失败，请查看！" + ";");
                    }
                }

                cerUtilsVos.add(cerUtilsVo);

                TrainingCertificatesDO trainingCertificatesDO = new TrainingCertificatesDO();
                if (rsUserDo != null) {
                    trainingCertificatesDO.setUserId(rsUserDo.getId());//用户id
                } else {
                    trainingCertificatesDO.setUserId(rrUserDo.getId());//用户id
                }
                trainingCertificatesDO.setNumbers(cerNumbers);//证书编号
////                //转换一下图片路径，将反斜杠替换掉
//                String url = cerImgUrl.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
//                String imgUrl1 = url.replace("\\", "/");
//                trainingCertificatesDO.setImgUrl(imgUrl1);//证书图片
//                if (cType.equals("0")) {
//                    //转换一下图片路径，将反斜杠替换掉
//                    String url1 = cerImgUrlNoSale.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
//                    String imgUrl2 = url1.replace("\\", "/");
//                    trainingCertificatesDO.setImgUrlNosale(imgUrl2);//不带电子公章的证书图片链接
//                }
                trainingCertificatesDO.setState(0);//默认正常
                trainingCertificatesDO.setQueries(0);//查询次数
                trainingCertificatesDO.setGetTime(new Date());//获证时间
                trainingCertificatesDO.setOrgName(list.get(i).getWorkUnit());
                traCerDOList.add(trainingCertificatesDO);
            }
        }

        delProvinEhcahe(cType);

        if (list1.size() == 0) {
            boolean c = trainingCertificatesService.insertBatch(traCerDOList, traCerDOList.size());
            if (c) {
                if(cprofileId.equals(RecoveryId))
                    apittController.doTask12(cerUtilsVos,traCerDOList);//产后恢复
                else apittController.doTask11(cerUtilsVos,traCerDOList);//幼儿照护
                return Result.ok("成功导入" + list.size() + "条数据");
            } else {
                return Result.fail("培训证书信息导入错误，请稍后重试或联系管理员");
            }
        } else {
            //导入失败，删除已导入的图片
            for (int fi = 0; fi < list.size(); fi++) {
                if (StringUtils.isNotBlank(list.get(fi).getImageUrl())) {
                    String url = list.get(fi).getImageUrl().replace(ValuesUtil.returnUrl, ValuesUtil.localUrl);
                    String imgUrl = url.replace("\\", "/");
                    boolean b1 = fileUtil.DeleteFolder(imgUrl);
                    log.info("导入培训证书信息失败删除学员图片第" + (fi + 1) + "张，情况：" + b1);
                }
            }
            //导入失败，删除已导入的图片
            for (int fe = 0; fe < traCerDOList.size(); fe++) {
                if (StringUtils.isNotBlank(traCerDOList.get(fe).getImgUrl())) {
                    String url = traCerDOList.get(fe).getImgUrl().replace(ValuesUtil.returnUrl, ValuesUtil.localUrl);
                    String imgUrl = url.replace("\\", "/");
                    boolean b1 = fileUtil.DeleteFolder(imgUrl);
                    log.info("导入信息产生的证书图片（带公章）失败删除图片第" + (fe + 1) + "张，情况：" + b1);
                }
                if (cType.equals("0")) {
                    if (StringUtils.isNotBlank(traCerDOList.get(fe).getImgUrlNosale())) {
                        String url = traCerDOList.get(fe).getImgUrlNosale().replace(ValuesUtil.returnUrl, ValuesUtil.localUrl);
                        String imgUrl = url.replace("\\", "/");
                        boolean b1 = fileUtil.DeleteFolder(imgUrl);
                        log.info("导入信息产生的证书图片（不带公章）失败删除图片第" + (fe + 1) + "张，情况：" + b1);
                    }
                }
            }

            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
            //将list1存到缓存中
            EhCacheUtil.put("trainingCertificates" + this.getUserId(), jsonArray);
            return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
        }
    }

    /**
     * 导出错误信息
     *
     * @param request
     * @param response
     * @throws Exception
     * @author kl
     */
    @Log("导出错误信息")
    @GetMapping("/importError")
    @ResponseBody
    @Transactional
    @RequiresPermissions("jzweb:trainingCertificates:import")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("培训证书导入错误信息", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        String jsonArray = EhCacheUtil.get("trainingCertificates" + this.getUserId()).toString();
        JSONArray arrayList = JSONArray.parseArray(jsonArray);
        //转换为目标对象list
        List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
        workbook.write(response.getOutputStream());
    }

    /**
     * 判断是否有数据
     */
    @Log("判断是否有数据")
    @RequestMapping("/isDataNull")
    @RequiresPermissions("jzweb:trainingCertificates:import")
    @ResponseBody
    public boolean isDataNull(HttpServletRequest request, HttpServletResponse response,String cprofileId, String cType, String numPeriods) {
        Map map = new HashMap();
        map.put("returnUrl", ValuesUtil.returnUrl);
        map.put("localUrl", ValuesUtil.localUrl);
        List<Map> imgUrls;
        if(cprofileId.equals(RecoveryId)) {
            if (cType.equals("0")) {
                map.put("type", "21");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("1")) {
                map.put("type", "41");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("2")) {
                map.put("type", "51");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("3")) {
                map.put("type", "61");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("4")) {
                map.put("type", "71");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("5")){
                map.put("type", "81");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }else if (cType.equals("6")){
                map.put("type", "11");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }else{
                map.put("type", "31");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }
        }else{
            if (cType.equals("0")) {
                map.put("type", "20");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("1")) {
                map.put("type", "40");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("2")) {
                map.put("type", "50");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("3")) {
                map.put("type", "60");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("4")) {
                map.put("type", "70");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("5")){
                map.put("type", "80");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }else if (cType.equals("6")){
                map.put("type", "10");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }else{
                map.put("type", "30");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }
        }
        System.out.println(map.get("type")+"  "+imgUrls.size());
        numPeriods = WithZoreUtil.frontCompWithZore(Integer.parseInt(numPeriods), 2);

        if (imgUrls != null && imgUrls.size() > 0) {
            List<String> imgUrlEnd = new ArrayList<>();
            //根据查询出的数据，拆解进行数据比较，清洗出相应的证书信息导出
            for (Map map1 : imgUrls) {
                if(map1.containsKey("imageUrl")){
                    if (map1.get("numbers") != null || map1.get("numbers") != "") {
                        String nums = map1.get("numbers").toString().substring(map1.get("numbers").toString().length() - 6, map1.get("numbers").toString().length() - 4);
                        if (numPeriods.equals(nums)) {
                            if (map1.get("imageUrl") != null || map1.get("imageUrl") != "") {
                                imgUrlEnd.add(map1.get("imageUrl").toString());
                            }
                        }
                    }
                }

            }

            if (imgUrlEnd == null || imgUrlEnd.size() < 1) {
                return false;
            }

            return true;
        } else {
            return false;
        }
    }

    /**
     * 导出证书PDF文件
     */
    @Log("导出证书PDF文件")
    @RequestMapping("/exportPdf")
    @RequiresPermissions("jzweb:trainingCertificates:import")
    @ResponseBody
    public void exportPdf(HttpServletRequest request, HttpServletResponse response, String cType, String numPeriods, String region,String cprofileId) {
        Map map = new HashMap();
        map.put("returnUrl", ValuesUtil.returnUrl);
        map.put("localUrl", ValuesUtil.localUrl);
        List<Map> imgUrls;
        List<Map> regAll=new ArrayList<>();
        //查询字典表中配置参数
       // DictDO dictDO= dictService.selectById(region);

        if(cprofileId.equals(RecoveryId)) {
            if (cType.equals("0")) {
                map.put("type", "21");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("1")) {
                map.put("type", "41");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("2")) {
                map.put("type", "51");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("3")) {
                map.put("type", "61");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("4")) {
                map.put("type", "71");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("5")){
                map.put("type", "81");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }else if (cType.equals("6")){
                map.put("type", "11");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }else{
                map.put("type", "31");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }
        }else{
            if (cType.equals("0")) {
                map.put("type", "20");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("1")) {
                map.put("type", "40");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("2")) {
                map.put("type", "50");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("3")) {
                map.put("type", "60");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("4")) {
                map.put("type", "70");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            } else if (cType.equals("5")){
                map.put("type", "80");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }else if (cType.equals("6")){
                map.put("type", "10");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }else{
                map.put("type", "30");
                imgUrls = trainingCertificatesService.selImgUrls(map);
            }
        }



            //根据省份筛选
            for(Map map1:imgUrls){
                String sss= map1.get("numbers").toString().substring(4,6);

                if(StringUtils.isNotBlank(region)&&StringUtils.isNotBlank(numPeriods)){

//                 if(sss.equals(region)){
//                    regAll.add(map1);
//                  }
                    String sss1= map1.get("numbers").toString().substring(10,12);
                    if(Integer.valueOf(sss1)==Integer.valueOf(numPeriods)&&sss.equals(region)){
                       regAll.add(map1);
                    }


                  }else if(StringUtils.isNotBlank(numPeriods)){
                        String sss1= map1.get("numbers").toString().substring(10,12);
                        if(Integer.valueOf(sss1)==Integer.valueOf(numPeriods)){
                                    regAll.add(map1);
                        }
                }else if(StringUtils.isNotBlank(region)){
                    String sss2= map1.get("numbers").toString().substring(4,6);
                    if(sss2.equals(region)){
                        regAll.add(map1);
                    }
                }




        }


        imgUrls=regAll;
        numPeriods = WithZoreUtil.frontCompWithZore(Integer.parseInt(numPeriods), 2);

        if (imgUrls != null && imgUrls.size() > 0) {
            List<String> imgUrlEnd = new ArrayList<>();
            //根据查询出的数据，拆解进行数据比较，清洗出相应的证书信息导出
            for (Map map1 : imgUrls) {
                if(map1.containsKey("imageUrl")){
                    if (map1.get("numbers") != null || map1.get("numbers") != "") {
                        String nums = map1.get("numbers").toString().substring(map1.get("numbers").toString().length() - 6, map1.get("numbers").toString().length() - 4);
                        if (numPeriods.equals(nums)) {
                            if (map1.get("imageUrl") != null || map1.get("imageUrl") != "") {
                                imgUrlEnd.add(map1.get("imageUrl").toString());
                            }
                        }
                    }
                }

            }

            if (imgUrlEnd == null || imgUrlEnd.size() < 1) {
                throw new IFastApiException(ApiEnumError.NOCer.getCodeStr());
            }

            String paths;
            if (cType.equals("0")) {
                paths = "师资培训第" + numPeriods + "期证书信息";
            } else if (cType.equals("1")) {
            	paths = "考评员培训第" + numPeriods + "期证书信息";
            }else if(cType.equals("2")){
                paths = "考务技术员培训第" + numPeriods + "期证书信息";
            }else if(cType.equals("3")){
            	paths = "考务技术员培训第" + numPeriods + "期结业证书信息";
            }else if(cType.equals("4")){
                paths = "督导员培训第" + numPeriods + "期证书信息";
            }else if(cType.equals("5")){
            	paths = "督导考务技术员培训第" + numPeriods + "期结业证书信息";
            }else if (cType.equals("6")){
                paths = "高级师资培训第" + numPeriods + "期结业证书信息";
            }else{
                paths = "高级考评员培训第" + numPeriods + "期结业证书信息";
            }

            try {
                this.creatPdf(paths, imgUrlEnd, cType);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }

            try {
                // path是指欲下载的文件的路径。
                File file = new File(ValuesUtil.localUrl + "/work/" + paths + ".pdf");
                String filepath = file.getPath();

                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(filepath));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + new String((paths + ".pdf").getBytes(), "iso-8859-1"));
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else {
            throw new IFastApiException(ApiEnumError.NOCer.getCodeStr());
        }
    }

    public void creatPdf(String pdfName, List<String> imgUrls, String cType) throws IOException, DocumentException {
        Rectangle pageSize;
        // 第一步，实例化一个document对象
        if (cType.equals("0")||cType.equals("3")||cType.equals("5")||cType.equals("6")) {
            pageSize = new Rectangle(1123F, 794F);
        } else {
            pageSize = new Rectangle(705F, 983F);
        }

        Document document = new Document(pageSize, 50, 50, 0, 50);
        // 设置相关的参数
        ITextPdfUtil.setParameters(document, "开发者", "测试", "测试 开发者 调试", "lance", "lance");
        // 第二步，设置要到出的路径
        try {
            FileOutputStream out = new FileOutputStream(ValuesUtil.localUrl + "/work/" + pdfName + ".pdf");
            // 第三步，将pdf文件输出到磁盘
            PdfWriter writer = PdfWriter.getInstance(document, out);
            // 第四步，打开生成的pdf文件
            document.open();
            // 第五步，往pdf文档中添加证书图片
            for (int i = 0; i < imgUrls.size(); i++) {
                File file=new  File(imgUrls.get(i));
                if(file.exists()){
                    Image image = Image.getInstance(imgUrls.get(i));
                    image.setAlignment(Element.ALIGN_CENTER);//设置元素居中
                    document.add(image);


       }
    }
            // 第八步，关闭document
            document.close();
            //文件输出至服务器
            String pdffilepath = ValuesUtil.localUrl + "\\work\\" + pdfName + ".pdf";
            ITextPdfUtil.doAddWaterMark(pdffilepath, pdfName, 38, "255, 200, 0", "4, 550", 10);


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


}
